import { onMounted, onUnmounted } from 'vue'
import _ from 'lodash'

export default function useScalePage(options) {
  const resieFunc = _.throttle(() => {
    triggerScale()
  }, 100)

  onMounted(() => {
    triggerScale()

    window.addEventListener('resize', resieFunc)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resieFunc)
  })
  // 大屏适配
  function triggerScale() {
    // 设计稿: 1920 * 1080
    // 目标适配 1920 * 1080 3840 * 2160(2*2) 7680 * 2160（4*2）

    // 1.设计稿尺寸
    let targetX = options.targetX || 1920
    let targetY = options.targetY || 1080
    let targetRatio = options.targetRatio || 16 / 9

    // 2.获取当前设备（浏览器）的宽度
    let currentX =
      document.documentElement.clientWidth || document.body.clientWidth
    let currentY =
      document.documentElement.clientHeight || document.body.clientHeight
    // 3.计算缩放比例
    let scaleRatio = currentX / targetX
    let currentRatio = currentX / currentY

    // 超宽屏
    if (currentRatio > targetRatio) {
      scaleRatio = currentY / targetY
      document.body.style = `width: ${targetX}px; height: ${targetY}px; transform: scale(${scaleRatio}) translateX(-50%); left: 50%;`
    } else {
      // 4.开始缩放网页
      document.body.style = `width: ${targetX}px; height: ${targetY}px; transform: scale(${scaleRatio})`
    }
  }
}
